// 将辅助函数保持在全局作用域
function formatDate(date) {
    return new Intl.DateTimeFormat('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    }).format(date);
}

function getStatusClass(conclusionType) {
    switch (conclusionType) {
        case 1: return 'status-success';
        case 2: return 'status-error';
        case 3: return 'status-warning';
        default: return '';
    }
}

function getTypeName(type) {
    const typeMap = {
        1: '涉黄',
        2: '暴恐',
        3: '恶心图像',
        4: '广告',
        5: '政治人物',
        6: '图像质量',
    };
    return typeMap[type] || `未知类型(${type})`;
}

// 显示审核详情的函数
function showAuditDetails(result) {
    // 创建模态框
    const modal = document.createElement('div');
    modal.className = 'audit-modal';
    
    // 获取审核结果的详细信息
    const conclusionType = result.result.conclusionType;
    const conclusion = result.result.conclusion;
    const details = result.result.data || [];
    
    const content = `
        <div class="modal-content">
            <div class="modal-header">
                <h3>审核详情</h3>
                <button class="close-btn">&times;</button>
            </div>
            <div class="modal-body">
                <div class="audit-info">
                    <p><strong>图片来源：</strong>${result.image_url ? '网络图片' : '本地上传'}</p>
                    ${result.image_url ? `<p><strong>图片URL：</strong>${result.image_url}</p>` : 
                                       `<p><strong>文件名：</strong>${result.filename}</p>`}
                    <p><strong>审核结果：</strong>
                        <span class="${getStatusClass(conclusionType)}">${conclusion}</span>
                    </p>
                    ${details.length > 0 ? '<h4>不合规原因：</h4>' : ''}
                    ${details.length > 0 ? `
                        <ul class="audit-details">
                            ${details.map(item => `
                                <li>
                                    <span class="detail-type">${getTypeName(item.type)}</span>
                                    <span class="detail-msg">${item.msg}</span>
                                    ${item.probability ? 
                                        `<span class="detail-probability">可能性：${(item.probability * 100).toFixed(2)}%</span>` 
                                        : ''}
                                </li>
                            `).join('')}
                        </ul>
                    ` : '<p>未发现不合规内容</p>'}
                </div>
            </div>
        </div>
    `;
    
    modal.innerHTML = content;
    document.body.appendChild(modal);
    
    // 添加关闭功能
    const closeBtn = modal.querySelector('.close-btn');
    closeBtn.onclick = () => modal.remove();
    modal.onclick = (e) => {
        if (e.target === modal) modal.remove();
    };
}

// 添加删除和审核函数到全局作用域
async function deleteImage(filename) {
    if (!confirm(`确定要删除图片 ${filename} 吗？`)) {
        return;
    }
    
    try {
        const response = await fetch(`/delete/${filename}`, {
            method: 'DELETE'
        });
        
        if (!response.ok) throw new Error('删除失败');
        
        // 重新加载图片列表
        window.imageAudit.loadImages();
    } catch (error) {
        console.error('删除失败:', error);
        alert('删除失败，请重试');
    }
}

async function auditImage(filename) {
    try {
        const response = await fetch('/audit', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ filename })
        });
        
        if (!response.ok) throw new Error('审核失败');
        
        const result = await response.json();
        // 重新加载图片列表
        window.imageAudit.loadImages();
    } catch (error) {
        console.error('审核失败:', error);
        alert('审核失败，请重试');
    }
}

async function auditAllImages() {
    if (!confirm('确定要审核所有未审核的图片吗？')) {
        return;
    }
    
    try {
        const response = await fetch('/audit-all', {
            method: 'POST'
        });
        
        if (!response.ok) throw new Error('审核失败');
        
        const results = await response.json();
        // 重新加载图片列表
        window.imageAudit.loadImages();
        
        // 显示审核结果摘要
        const successCount = results.filter(r => !r.error).length;
        const failCount = results.filter(r => r.error).length;
        alert(`审核完成\n成功: ${successCount}\n失败: ${failCount}`);
    } catch (error) {
        console.error('审核失败:', error);
        alert('审核失败，请重试');
    }
}

function exportResult(filename) {
    window.location.href = `/export/${filename}`;
}

function exportAllResults() {
    window.location.href = '/export-all';
}

function initializeImageAudit() {
    const uploadArea = document.getElementById('upload-area');
    const uploadContent = document.getElementById('upload-content');
    const imageUpload = document.getElementById('image-upload');
    const imageList = document.getElementById('image-list');
    
    let currentFiles = [];

    // 加载图片列表
    async function loadImages() {
        try {
            const response = await fetch('/list');
            const data = await response.json();
            
            // 显示未审核的图片
            const uncheckedHtml = data.unchecked.map(image => `
                <div class="image-item unchecked">
                    <img src="${image.path}" alt="${image.filename}">
                    <div class="image-info">
                        <span>${image.filename}</span>
                        <div class="button-group">
                            <button onclick="auditImage('${image.filename}')">审核</button>
                            <button class="delete-btn" onclick="deleteImage('${image.filename}')">删除</button>
                        </div>
                    </div>
                </div>
            `).join('');
            
            // 显示已审核的图片
            const checkedHtml = data.checked.map(image => {
                const conclusionType = image.result.conclusionType;
                const conclusion = image.result.conclusion;
                const details = image.result.data || [];
                
                return `
                    <div class="image-item checked">
                        <div class="image-container ${getStatusClass(conclusionType)}-border">
                            <img src="${image.path}" alt="${image.filename}" 
                                 onclick="showAuditDetails(${JSON.stringify(image)})"
                                 title="点击查看详情">
                            ${conclusionType > 1 ? `
                                <div class="audit-overlay">
                                    <div class="audit-summary">
                                        ${details.map(item => `
                                            <div class="audit-reason">
                                                <span class="reason-type">${getTypeName(item.type)}</span>
                                                ${item.probability ? 
                                                    `<span class="reason-probability">${(item.probability * 100).toFixed(0)}%</span>` 
                                                    : ''}
                                            </div>
                                        `).join('')}
                                    </div>
                                </div>
                            ` : ''}
                        </div>
                        <div class="image-info">
                            <span>${image.filename}</span>
                            <span class="${getStatusClass(conclusionType)}">
                                ${conclusion}
                            </span>
                            <div class="button-group">
                                <button onclick="exportResult('${image.filename}')">导出结果</button>
                                <button class="delete-btn" onclick="deleteImage('${image.filename}')">删除</button>
                            </div>
                        </div>
                    </div>
                `;
            }).join('');
            
            imageList.innerHTML = `
                <div class="unchecked-section">
                    <h3>待审核图片</h3>
                    ${data.unchecked.length > 0 ? 
                        `<button class="audit-all-btn" onclick="auditAllImages()">审核全部</button>` : 
                        ''}
                    <div class="image-grid">${uncheckedHtml}</div>
                </div>
                <div class="checked-section">
                    <h3>已审核图片</h3>
                    ${data.checked.length > 0 ? 
                        `<button class="export-all-btn" onclick="exportAllResults()">导出全部结果</button>` : 
                        ''}
                    <div class="image-grid">${checkedHtml}</div>
                </div>
            `;
        } catch (error) {
            console.error('加载图片列表失败:', error);
        }
    }

    // 上传图片
    async function uploadImages(files) {
        const formData = new FormData();
        Array.from(files).forEach(file => {
            formData.append('image', file);
        });

        try {
            const response = await fetch('/upload', {
                method: 'POST',
                body: formData
            });
            
            if (!response.ok) throw new Error('上传失败');
            
            // 重新加载图片列表
            await loadImages();
        } catch (error) {
            console.error('上传失败:', error);
            alert('上传失败，请重试');
        }
    }

    // 初始化上传区域
    function initializeUpload() {
        uploadArea.addEventListener('click', () => imageUpload.click());
        
        imageUpload.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                uploadImages(e.target.files);
            }
            e.target.value = '';
        });

        // 拖拽上传
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });

        uploadArea.addEventListener('dragleave', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            if (e.dataTransfer.files.length > 0) {
                uploadImages(e.dataTransfer.files);
            }
        });
    }

    // 添加网络图片审核功能
    const imageUrlInput = document.getElementById('image-url');
    const urlAuditBtn = document.getElementById('url-audit-btn');
    
    async function auditUrlImage() {
        const url = imageUrlInput.value.trim();
        if (!url) {
            alert('请输入图片URL');
            return;
        }
        
        try {
            urlAuditBtn.disabled = true;
            
            const response = await fetch('/audit-url', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ url })
            });
            
            if (!response.ok) throw new Error('审核失败');
            
            const result = await response.json();
            
            // 显示审核结果
            showAuditDetails({
                filename: '网络图片',
                result: result,
                image_url: result.image_url
            });
            
        } catch (error) {
            console.error('审核失败:', error);
            alert('审核失败，请重试');
        } finally {
            urlAuditBtn.disabled = false;
            imageUrlInput.value = ''; // 清空输入框
        }
    }
    
    // 添加审核按钮事件
    urlAuditBtn.addEventListener('click', auditUrlImage);
    
    // 添加回车键触发审核
    imageUrlInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            auditUrlImage();
        }
    });

    // 初始化
    initializeUpload();
    loadImages();

    // 将 loadImages 函数暴露到全局
    window.imageAudit = {
        loadImages
    };
}

// 初始化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeImageAudit);
} else {
    initializeImageAudit();
} 